package com.qf.config;

import ch.qos.logback.core.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.config
 * @Description: redis实现分布式锁,加锁,解锁工具
 * @Date 2022/7/11 21:01
 */
@Component
public class RedisLockUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加锁
     * @param key           锁的名字
     * @param value        锁的值
     * @param second     锁定的超时时间
     * @return
     */
    public boolean lock(String key,String value,int second){
        return redisTemplate.opsForValue().setIfAbsent(key,value,second, TimeUnit.SECONDS);
    }

    /**
     * 解锁
     * @param key  锁的名字
     */
    public void unlock(String key){
        redisTemplate.delete(key);
    }
}
